import uuid

from flasgger import swag_from
from flask import g, request
from flask.views import MethodView
from flask_jwt_extended import create_access_token

from app.auth.models import User
from app.extensions import json_response
from utils.base import login_require


class Login(MethodView):
    @login_require
    @swag_from("./apidocs/get_login.yaml")
    def get(self):
        return json_response(data={"user_name": g.user_name, "user_id": g.user_id})

    @swag_from("./apidocs/post_login.yaml")
    def post(self):
        body = request.json
        user_name, password = body.get("user_name"), body.get("password")
        user = User.get_or_none(user_name=user_name)

        if not user:
            user_info = {
                "user_id": uuid.uuid1().hex,
                "user_name": user_name,
                "password": password,
            }
            user = User.create(**user_info)
        elif not (user_name == user.user_name and user.check_password(password)):
            return json_response(code=404)

        user_info = {"user_id": user.user_id, "user_name": user.user_name}
        token = create_access_token(identity=user_info)
        return json_response(data={"token": f"Bearer {token}", "user_name": user_name})
